import os
import requests
import json
import time

# https://docs.github.com/en/rest/search/search?apiVersion=2022-11-28#search-repositories

def download_github_most_stars(filename):
  star_items = []

  for page in range (1,6):
    res = requests.get(f'https://api.github.com/search/repositories?q=stars:>10000&sort=stars&order=desc&per_page=100&page={page}')
    star_items.extend(res.json()['items'])

  with open(filename, 'w') as f:
    json.dump(star_items, f, indent=2)


def download_github_most_forks(filename, count = 1000):
  star_items = []

  for page in range (1,(count//100)+1):
    res = requests.get(f'https://api.github.com/search/repositories?q=forks:>1000&sort=forks&order=desc&per_page=100&page={page}')
    star_items.extend(res.json()['items'])

  with open(filename, 'w') as f:
    json.dump(star_items, f, indent=2)


if __name__ == "__main__":
  try:
    date_str = time.strftime("%Y_%m_%d", time.localtime())

    download_github_most_stars(f'data/most_stars/{date_str}.json')
    # download_github_most_forks(f'data/most_forks/{date_str}.json', 1000)

  except Exception as e:
    print(e)